package com.fengwei.security;

import cn.hutool.core.util.StrUtil;
import com.fengwei.util.MdmsConsts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 自定义认证器
 */
@Component
public class SelfAuthenticationProvider implements AuthenticationProvider {
    private final static Logger logger = LoggerFactory.getLogger(SelfAuthenticationProvider.class);

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private Map springSecurityUserTypeMap;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {


        //获取用户登录输入的信息
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        //获取用户
        String userType = (String) springSecurityUserTypeMap.get(userName);
        if (StrUtil.hasEmpty(userType)) {
            logger.debug("用户还未登录");
            throw new BadCredentialsException("用户还未登录");
        }
        springSecurityUserTypeMap.remove(userName);

        //用注册用户时相同的加密方式加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        User user = new User(userName,
                passwordEncoder.encode("123456"),
                AuthorityUtils.commaSeparatedStringToAuthorityList(getSpringSecurityRole(userType)));

//        //进行密码比对
//        if (!encoder.matches(password, userInfo.getPassword())) {
//            throw new BadCredentialsException("用户名密码不正确，请重新登陆！");
//        }

        //比对成功返回token令牌
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userName, password,
                user.getAuthorities());
        logger.debug("=============");
        return usernamePasswordAuthenticationToken;
    }

    /**
     * 如果该AuthenticationProvider支持传入的Authentication对象，则返回true
     *
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

    private String getSpringSecurityRole(String userType) {
        String role = "";
        if (MdmsConsts.USER_TYPE_0.equals(userType)) {
            role = "ROLE_USER";
        } else if (MdmsConsts.USER_TYPE_1.equals(userType)) {
            role = "ROLE_DBA";
        } else if (MdmsConsts.USER_TYPE_99.equals(userType)) {
            role = "ROLE_ADMIN";
        } else {
            role = "ROLE_NONE";
        }
        return role;
    }
}